package com.atguigu.spzx.manager.Interceptor;

import com.atguigu.spyx.model.common.ResultCodeEnum;
import com.atguigu.spyx.model.common.com.atguigu.spyx.model.entity.sys.SysUser;
import com.atguigu.spyx.model.exception.SpzxException;
import com.atguigu.spzx.common.util.AuthUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author LT
 * @create 2023-11-03-10:13
 */
@Component
public class LoginAuthInterceptor implements HandlerInterceptor {
    public static final ThreadLocal<SysUser> THREAD_LOCAL = new ThreadLocal<>();

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        if (StringUtils.equals("OPTIONS",method)){
            return true;
        }
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            throw new SpzxException(ResultCodeEnum.LOGIN_EXPIRE_ERROR,null);
        }
        Object sysUser = redisTemplate.opsForValue().get("sys:user:login" + token);
        if (sysUser==null){
            throw new SpzxException(ResultCodeEnum.LOGIN_EXPIRE_ERROR,null);
        }
        THREAD_LOCAL.set((SysUser) sysUser);

        AuthUtils.set((SysUser) sysUser);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        THREAD_LOCAL.remove();

    }
}
